package org.xenon.vote.listener;

import org.xenon.vote.model.pojo.po.Judge;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

@WebListener()
public class OnlineJudgeListener implements HttpSessionListener {
    private static final HashMap<String, Judge> onlineJudge = new HashMap<>();//session, Judge
    @Override
    public void sessionCreated(HttpSessionEvent se) {
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        onlineJudge.remove(se.getSession().getId());
    }

    /**
     * 登录裁判的时候使用
     */
    public static void login(Judge judge, String sessionId){
        onlineJudge.put(sessionId, judge);
    }

    /**
     * 获取用户的在线裁判
     * @param mail 用户邮箱
     */
    public static List<Judge> getOnline(String mail){
        Collection<Judge> judges = onlineJudge.values();
        ArrayList<Judge> list = new ArrayList<>();
        for (Judge j : judges)
            if(j.getOwner().equals(mail)) list.add(j);
        return list;
    }
}
